<?php namespace dmq;

/**
* A database class
*
* The database class is used to create a connection to 
* the database and deal with questions to and from the database
*
* @author dmq (master@dmq.se)
*/
class Database
{
	private $mysqli = null;
	private $transactionStatus = true;

	// Open db connection.
	public function open()
	{
		$this->mysqli = @new \mysqli( Settings::DB_HOST, Settings::DB_USER, Settings::DB_PASSWORD, Settings::DB_NAME );
		if ( $this->mysqli->connect_errno )
		{
			echo 'Could not connect to the database.';
			die();
		}
	}

	// Open and return a new connection.
	public function openNew()
	{
		$connection = new Database();
		$connection->open();

		return $connection;
	}

	// Close db connection.
	public function close()
	{
		$this->mysqli->close();
		$this->mysqli = null;
	}

	// Return prepare statement.
	public function prepare( $sql )
	{
		return $this->mysqli->prepare( $sql );
	}

	// Last insert id.
	public function lastInsertId()
	{
		return $this->mysqli->insert_id;
	}

	public function startTransaction()
	{
		$this->mysqli->autocommit( false );
		$this->transactionStatus = true;
	}

	public function execute( $stmt )
	{
		return $this->transactionStatus = !!$stmt->execute();
	}

	public function endTransaction()
	{
		if ( !$this->transactionStatus )
		{
			$this->mysqli->rollback();
		}
		else
		{
			$this->mysqli->commit();
		}

		$this->mysqli->autocommit( true );

		return $this->transactionStatus;
	}
}
